<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>小学生词语抽查</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            padding: 40px;
            text-align: center;
            max-width: 600px;
            width: 100%;
        }

        h1 {
            color: #333;
            margin-bottom: 30px;
            font-size: 2.5em;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
        }

        .wordlist-selector {
            margin-bottom: 30px;
        }

        .wordlist-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }

        .wordlist-item {
            padding: 20px;
            background: white;
            border-radius: 12px;
            cursor: pointer;
            transition: all 0.3s ease;
            border: 2px solid #e0e0e0;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .wordlist-item:hover {
            background: #f5f5f5;
            border-color: #2196F3;
            transform: translateY(-2px);
            box-shadow: 0 4px 16px rgba(0,0,0,0.15);
        }

        .wordlist-item.selected {
            background: #e8f5e8;
            border-color: #4CAF50;
        }

        .wordlist-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
            margin-bottom: 8px;
        }

        .wordlist-description {
            font-size: 14px;
            color: #666;
            margin-bottom: 8px;
        }

        .wordlist-count {
            font-size: 12px;
            color: #888;
            font-weight: bold;
        }

        .loading {
            text-align: center;
            color: #666;
            padding: 20px;
            font-style: italic;
        }

        .error {
            text-align: center;
            color: #f44336;
            padding: 20px;
            font-style: italic;
        }

        .word-display {
            margin: 40px 0;
        }

        .word {
            font-size: 3em;
            color: #333;
            font-weight: bold;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
            min-height: 80px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .controls {
            margin-top: 30px;
        }

        .btn {
            padding: 15px 30px;
            margin: 0 10px;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 16px;
            font-weight: bold;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: #2196F3;
            color: white;
        }

        .btn-primary:hover {
            background: #1976D2;
            transform: translateY(-2px);
        }

        .btn-secondary {
            background: #FF9800;
            color: white;
        }

        .btn-secondary:hover {
            background: #F57C00;
            transform: translateY(-2px);
        }

        .file-info {
            margin-top: 20px;
            color: #666;
            font-size: 14px;
        }

        .word-count {
            margin-top: 10px;
            color: #888;
            font-size: 14px;
        }

        .pinyin {
            font-size: 0.4em;
            color: #666;
            margin-bottom: 10px;
            font-weight: normal;
        }

        .pinyin-toggle {
            margin: 20px 0;
        }

        .toggle-switch {
            position: relative;
            display: inline-block;
            width: 60px;
            height: 34px;
            margin-left: 10px;
        }

        .toggle-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 34px;
        }

        .slider:before {
            position: absolute;
            content: "";
            height: 26px;
            width: 26px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }

        input:checked + .slider {
            background-color: #2196F3;
        }

        input:checked + .slider:before {
            transform: translateX(26px);
        }

        .word-with-pinyin {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }

        .answer-buttons {
            margin: 20px 0;
            display: flex;
            justify-content: center;
            gap: 20px;
        }

        .answer-btn {
            padding: 12px 24px;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 16px;
            font-weight: bold;
            transition: all 0.3s ease;
            min-width: 100px;
        }

        .answer-btn.correct {
            background: #4CAF50;
            color: white;
        }

        .answer-btn.correct:hover {
            background: #45a049;
            transform: translateY(-2px);
        }

        .answer-btn.wrong {
            background: #f44336;
            color: white;
        }

        .answer-btn.wrong:hover {
            background: #da190b;
            transform: translateY(-2px);
        }

        .answer-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
        }

        .stats {
            margin-top: 20px;
            padding: 15px;
            background: #f5f5f5;
            border-radius: 10px;
            display: flex;
            justify-content: space-around;
            text-align: center;
        }

        .stat-item {
            display: flex;
            flex-direction: column;
        }

        .stat-number {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 5px;
        }

        .stat-label {
            font-size: 14px;
            color: #666;
        }

        .stat-number.correct {
            color: #4CAF50;
        }

        .stat-number.wrong {
            color: #f44336;
        }

        .stat-number.total {
            color: #2196F3;
        }

        .stat-number.accuracy {
            color: #FF9800;
        }

        .stat-number.review {
            color: #9C27B0;
        }

        .word-info {
            margin-top: 10px;
            font-size: 12px;
            color: #666;
            height: 20px;
        }

        .box-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 5px;
        }

        .box-1 { background-color: #f44336; }
        .box-2 { background-color: #ff9800; }
        .box-3 { background-color: #4caf50; }
        .box-4 { background-color: #2196f3; }
        .box-5 { background-color: #9c27b0; }
    </style>
</head>
<body>
    <div class="container">
        <h1>📚 小学生词语抽查</h1>
        
        <div class="wordlist-selector">
            <div id="wordlistGrid" class="wordlist-grid">
                <div class="loading">正在加载词语列表...</div>
            </div>
            <div id="fileInfo" class="file-info"></div>
            <div id="wordCount" class="word-count"></div>
        </div>

        <div class="pinyin-toggle">
            <label>显示拼音</label>
            <label class="toggle-switch">
                <input type="checkbox" id="pinyinToggle" checked>
                <span class="slider"></span>
            </label>
        </div>

        <div class="word-display">
            <div id="currentWord" class="word">请先选择词语文件</div>
            <div id="wordInfo" class="word-info"></div>
        </div>

        <div class="answer-buttons">
            <button id="correctBtn" class="answer-btn correct" disabled>✓ 认识</button>
            <button id="wrongBtn" class="answer-btn wrong" disabled>✗ 不认识</button>
        </div>

        <div class="controls">
            <button id="nextBtn" class="btn btn-primary" disabled>下一个词语</button>
            <button id="resetBtn" class="btn btn-secondary" disabled>重新开始</button>
        </div>

        <div class="stats">
            <div class="stat-item">
                <div id="correctCount" class="stat-number correct">0</div>
                <div class="stat-label">认识</div>
            </div>
            <div class="stat-item">
                <div id="wrongCount" class="stat-number wrong">0</div>
                <div class="stat-label">不认识</div>
            </div>
            <div class="stat-item">
                <div id="totalCount" class="stat-number total">0</div>
                <div class="stat-label">总计</div>
            </div>
            <div class="stat-item">
                <div id="accuracy" class="stat-number accuracy">0%</div>
                <div class="stat-label">正确率</div>
            </div>
            <div class="stat-item">
                <div id="reviewCount" class="stat-number review">0</div>
                <div class="stat-label">待复习</div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/pinyin-pro/dist/index.js"></script>
    <script>
        let words = [];
        let currentWordIndex = 0;
        let usedWords = [];
        let pinyinCache = {};
        let correctCount = 0;
        let wrongCount = 0;
        let totalCount = 0;
        let hasAnswered = false;
        let currentWord = null;
        
        // 莱特纳系统
        let leitnerBoxes = {
            box1: [], // 第1盒：每天复习
            box2: [], // 第2盒：每2天复习
            box3: [], // 第3盒：每4天复习
            box4: [], // 第4盒：每7天复习
            box5: []  // 第5盒：每15天复习（已掌握）
        };
        
        // 词语列表管理
        let wordLists = [];
        let selectedList = null;

        const fileInfo = document.getElementById('fileInfo');
        const wordCount = document.getElementById('wordCount');
        const wordlistGrid = document.getElementById('wordlistGrid');
        const currentWordDiv = document.getElementById('currentWord');
        const nextBtn = document.getElementById('nextBtn');
        const resetBtn = document.getElementById('resetBtn');
        const pinyinToggle = document.getElementById('pinyinToggle');
        const correctBtn = document.getElementById('correctBtn');
        const wrongBtn = document.getElementById('wrongBtn');
        const correctCountDiv = document.getElementById('correctCount');
        const wrongCountDiv = document.getElementById('wrongCount');
        const totalCountDiv = document.getElementById('totalCount');
        const accuracyDiv = document.getElementById('accuracy');
        const reviewCountDiv = document.getElementById('reviewCount');
        const wordInfoDiv = document.getElementById('wordInfo');

        nextBtn.addEventListener('click', showNextWord);
        resetBtn.addEventListener('click', resetWords);
        pinyinToggle.addEventListener('change', togglePinyin);
        correctBtn.addEventListener('click', markCorrect);
        wrongBtn.addEventListener('click', markWrong);

        // 页面加载时获取JSON数据
        loadWordLists();

        async function loadWordLists() {
            try {
                const response = await fetch('word_lists.json');
                if (!response.ok) {
                    throw new Error('无法加载词语列表');
                }
                
                const data = await response.json();
                wordLists = data.word_lists || [];
                
                if (wordLists.length === 0) {
                    wordlistGrid.innerHTML = '<div class="error">没有找到词语列表</div>';
                    return;
                }
                
                displayWordLists();
            } catch (error) {
                console.error('加载词语列表失败:', error);
                wordlistGrid.innerHTML = '<div class="error">加载词语列表失败，请检查文件是否存在</div>';
            }
        }

        function displayWordLists() {
            wordlistGrid.innerHTML = '';
            
            wordLists.forEach((list, index) => {
                const listItem = createWordlistItem(list, index);
                wordlistGrid.appendChild(listItem);
            });
        }

        function createWordlistItem(list, index) {
            const listItem = document.createElement('div');
            listItem.className = 'wordlist-item';
            listItem.innerHTML = `
                <div class="wordlist-title">${list.name}</div>
                <div class="wordlist-description">${list.description}</div>
                <div class="wordlist-count">${list.words.length} 个词语</div>
            `;
            
            listItem.addEventListener('click', () => selectWordlist(list, listItem));
            return listItem;
        }

        function selectWordlist(list, listItem) {
            // 移除其他选中状态
            document.querySelectorAll('.wordlist-item').forEach(item => {
                item.classList.remove('selected');
            });
            
            // 选中当前列表
            listItem.classList.add('selected');
            selectedList = list;
            
            // 使用词语列表
            useWordlist(list);
        }

        function useWordlist(list) {
            words = list.words;
            
            if (words.length === 0) {
                alert('词语列表为空！');
                return;
            }

            // 初始化莱特纳系统
            initializeLeitnerSystem();

            fileInfo.textContent = `已加载: ${list.name}`;
            wordCount.textContent = `共 ${words.length} 个词语`;
            
            currentWordIndex = 0;
            usedWords = [];
            
            updateStats();
            showNextWord();
            
            nextBtn.disabled = false;
            resetBtn.disabled = false;
            correctBtn.disabled = false;
            wrongBtn.disabled = false;
        }

        function initializeLeitnerSystem() {
            // 清空所有盒子
            leitnerBoxes = {
                box1: [],
                box2: [],
                box3: [],
                box4: [],
                box5: []
            };
            
            // 将所有词语放入第1盒
            words.forEach(word => {
                leitnerBoxes.box1.push({
                    word: word,
                    lastReview: Date.now(),
                    correctCount: 0,
                    wrongCount: 0
                });
            });
        }

        
        async function showNextWord() {
            const wordData = selectNextWord();
            if (!wordData) {
                currentWordDiv.textContent = '🎉 所有词语已抽查完毕！';
                wordInfoDiv.textContent = '';
                correctBtn.disabled = true;
                wrongBtn.disabled = true;
                return;
            }

            currentWord = wordData;
            await displayWordWithPinyin(wordData.word);
            updateWordInfo(wordData);
            
            // 重置答题状态
            hasAnswered = false;
            correctBtn.disabled = false;
            wrongBtn.disabled = false;
        }

        function selectNextWord() {
            const now = Date.now();
            const candidates = [];
            
            // 检查每个盒子中的词语
            for (let boxNum = 1; boxNum <= 5; boxNum++) {
                const box = leitnerBoxes[`box${boxNum}`];
                const interval = getReviewInterval(boxNum);
                
                for (let wordData of box) {
                    const timeSinceLastReview = now - wordData.lastReview;
                    const isDue = timeSinceLastReview >= interval;
                    
                    if (isDue) {
                        candidates.push({
                            ...wordData,
                            boxNumber: boxNum,
                            priority: 6 - boxNum // 数字越小优先级越高
                        });
                    }
                }
            }
            
            if (candidates.length === 0) {
                return null;
            }
            
            // 按优先级排序，优先选择低盒子的词语
            candidates.sort((a, b) => {
                // 优先级高的先显示
                if (a.priority !== b.priority) {
                    return b.priority - a.priority;
                }
                
                // 同一盒子内，错误次数多的优先
                if (a.wrongCount !== b.wrongCount) {
                    return b.wrongCount - a.wrongCount;
                }
                
                // 随机选择
                return Math.random() - 0.5;
            });
            
            return candidates[0];
        }

        function getReviewInterval(boxNumber) {
            const intervals = {
                1: 0,      // 第1盒：立即复习
                2: 2 * 24 * 60 * 60 * 1000,  // 第2盒：2天
                3: 4 * 24 * 60 * 60 * 1000,  // 第3盒：4天
                4: 7 * 24 * 60 * 60 * 1000,  // 第4盒：7天
                5: 15 * 24 * 60 * 60 * 1000  // 第5盒：15天
            };
            return intervals[boxNumber] || 0;
        }

        function updateWordInfo(wordData) {
            const boxName = getBoxName(wordData.boxNumber);
            let info = `<span class="box-indicator box-${wordData.boxNumber}"></span>${boxName}`;
            
            if (wordData.wrongCount > 0) {
                info += ` | 错误: ${wordData.wrongCount}次`;
            }
            if (wordData.correctCount > 0) {
                info += ` | 正确: ${wordData.correctCount}次`;
            }
            
            wordInfoDiv.innerHTML = info;
        }

        function getBoxName(boxNumber) {
            const names = {
                1: '新词',
                2: '学习中',
                3: '熟悉',
                4: '掌握',
                5: '已精通'
            };
            return names[boxNumber] || '未知';
        }

        function resetWords() {
            if (!selectedList) return;
            
            currentWordIndex = 0;
            usedWords = [];
            correctCount = 0;
            wrongCount = 0;
            totalCount = 0;
            hasAnswered = false;
            currentWord = null;
            
            // 重新初始化莱特纳系统
            initializeLeitnerSystem();
            
            correctBtn.disabled = false;
            wrongBtn.disabled = false;
            wordInfoDiv.textContent = '';
            
            updateStats();
            showNextWord();
        }

        function markCorrect() {
            if (hasAnswered || !currentWord) return;
            
            // 更新统计数据
            currentWord.correctCount++;
            currentWord.lastReview = Date.now();
            
            correctCount++;
            totalCount++;
            hasAnswered = true;
            
            // 移动到下一个盒子
            moveToNextBox(currentWord);
            
            correctBtn.disabled = true;
            wrongBtn.disabled = true;
            
            updateStats();
            updateWordInfo(currentWord);
        }

        function markWrong() {
            if (hasAnswered || !currentWord) return;
            
            // 更新统计数据
            currentWord.wrongCount++;
            currentWord.lastReview = Date.now();
            
            wrongCount++;
            totalCount++;
            hasAnswered = true;
            
            // 移动回第1盒
            moveToBox1(currentWord);
            
            correctBtn.disabled = true;
            wrongBtn.disabled = true;
            
            updateStats();
            updateWordInfo(currentWord);
        }

        function moveToNextBox(wordData) {
            // 从当前盒子移除
            const currentBox = leitnerBoxes[`box${wordData.boxNumber}`];
            const index = currentBox.findIndex(item => item.word === wordData.word);
            if (index !== -1) {
                currentBox.splice(index, 1);
            }
            
            // 移动到下一个盒子
            const nextBoxNumber = Math.min(wordData.boxNumber + 1, 5);
            const nextBox = leitnerBoxes[`box${nextBoxNumber}`];
            
            nextBox.push({
                ...wordData,
                boxNumber: nextBoxNumber
            });
        }

        function moveToBox1(wordData) {
            // 从当前盒子移除
            const currentBox = leitnerBoxes[`box${wordData.boxNumber}`];
            const index = currentBox.findIndex(item => item.word === wordData.word);
            if (index !== -1) {
                currentBox.splice(index, 1);
            }
            
            // 移动回第1盒
            leitnerBoxes.box1.push({
                ...wordData,
                boxNumber: 1
            });
        }

        function updateStats() {
            correctCountDiv.textContent = correctCount;
            wrongCountDiv.textContent = wrongCount;
            totalCountDiv.textContent = totalCount;
            
            const accuracy = totalCount > 0 ? Math.round((correctCount / totalCount) * 100) : 0;
            accuracyDiv.textContent = accuracy + '%';
            
            // 计算待复习数量（第1-4盒的词语）
            let reviewCount = 0;
            for (let boxNum = 1; boxNum <= 4; boxNum++) {
                reviewCount += leitnerBoxes[`box${boxNum}`].length;
            }
            reviewCountDiv.textContent = reviewCount;
        }

        function getPinyin(text) {
            return new Promise((resolve, reject) => {
                if (pinyinCache[text]) {
                    resolve(pinyinCache[text]);
                    return;
                }

                try {
                    // 使用pinyin-pro本地获取拼音
                    const pinyin = pinyinPro.pinyin(text, { 
                        toneType: 'symbol', 
                        type: 'array' 
                    });
                    
                    if (pinyin && pinyin.length > 0) {
                        // 将数组转换为字符串，每个字拼音用空格分隔
                        const pinyinString = pinyin.join(' ');
                        pinyinCache[text] = pinyinString;
                        resolve(pinyinString);
                    } else {
                        reject(new Error('无法获取拼音'));
                    }
                } catch (error) {
                    console.error('获取拼音失败:', error);
                    reject(error);
                }
            });
        }

        async function displayWordWithPinyin(word) {
            if (!pinyinToggle.checked) {
                currentWordDiv.textContent = word;
                return;
            }

            try {
                const pinyin = await getPinyin(word);
                currentWordDiv.innerHTML = `
                    <div class="word-with-pinyin">
                        <div class="pinyin">${pinyin}</div>
                        <div>${word}</div>
                    </div>
                `;
            } catch (error) {
                console.error('显示拼音失败:', error);
                currentWordDiv.textContent = word;
            }
        }

        function togglePinyin() {
            if (words.length > 0 && currentWordDiv.textContent !== '请先选择词语文件' && currentWordDiv.textContent !== '🎉 所有词语已抽查完毕！') {
                const currentWord = words[currentWordIndex - 1] || words[0];
                if (currentWord) {
                    displayWordWithPinyin(currentWord);
                }
            }
        }
    </script>
</body>
</html>